package com.biz.primus.auth.controller;

import com.biz.primus.auth.feign.RoleFeignClient;
import com.biz.primus.auth.feign.UserFeignClient;
import com.biz.primus.common.vo.SpringPageVO;
import com.biz.primus.base.enums.CommonStatus;
import com.biz.primus.management.base.controller.AbstractBaseController;
import com.biz.primus.model.sso.account.vo.UserReqVo;
import com.biz.primus.model.sso.account.vo.UserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.annotation.Secured;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

@Controller
@RequestMapping("users")
@Secured("ROLE_USER")
public class UserController extends AbstractBaseController {
    private final UserFeignClient userFeignClient;

    private final RoleFeignClient roleFeignClient;

    @Autowired
    public UserController(UserFeignClient userFeignClient, RoleFeignClient roleFeignClient) {
        this.userFeignClient = userFeignClient;
        this.roleFeignClient = roleFeignClient;
    }

    @GetMapping
    @PreAuthorize("hasAuthority('OPT_USER_LIST')")
    public ModelAndView list(@ModelAttribute("UserVo") UserReqVo userReqVo) {
        //这是对查询条件的用户进行分页
        SpringPageVO<UserVo> userPage = userFeignClient.listUser(userReqVo);
        return new ModelAndView("user/list", "userPage", userPage);
    }

    @RequestMapping("edit")
    @PreAuthorize("hasAuthority('OPT_USER_EDIT')")
    public ModelAndView edit(@RequestParam("id") Long id) {
        UserVo User = userFeignClient.getUser(id);
        ModelAndView view = new ModelAndView("user/edit", "user", User);
        view.addObject("roles", roleFeignClient.findByStatus(CommonStatus.ENABLE));
        return view;
    }

    @RequestMapping("/save_edit")
    @PreAuthorize("hasAuthority('OPT_USER_EDIT')")
    public String save_edit(UserVo userVo, BindingResult result) {
        error(result);
        userFeignClient.createUser(userVo);
        return "redirect:/users.do";
    }



}
